import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Table, message} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {
    PAGE,
    TABLE,
    FORM_BIG_OPTIONS,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH,
} from '../constants';
import {PERMISSION} from './constants';
import Export from '../common/Export';
import routes from './routes';
import {hasPermissions, conventSorter, getObjById} from './utils';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import DropdownMenu from 'Shared/components/DropdownMenu';
const ButtonGroup = Button.Group;
const FormItem = Form.Item;
import WrappedTag from '../common/WrappedTag';
import styles from './style.css';
import ModeEdit from './ModeEdit';
class QueryPanel extends React.PureComponent {
    state = {
        loading: false,
        showPanel: false,
    };

    handleAbandon = id => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };

    onClickAdd= () => {
        if(!this.props.categoryName)
            return message.warn(this.props.intl.formatMessage({
                id: 'queryPanel.validate.message',
                defaultMessage: '请先选择左侧的故障原因分类'
            }));
        this.setState({
            currentId: '',
            showPanel: true
        });
    }
    onClickEdit = e => {
        const {id} = e.target.dataset;
        this.setState({
            currentId: id,
            showPanel: true
        });
    }

    onCancel = () => {
        this.setState({
            currentId: '',
            showPanel: false
        });
    }

    onSubmit = data => this.props.onClickUpdate(data).then(success => {
        this.setState({
            loading: false,
        });
        if(success)
            this.onCancel();
        return success;
    });
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({
                ...conventSorter(sorter),
                pageIndex: PAGE.index
            });
    };
    render() {
        const operations = [];
        const otherBtns = [];
        if(hasPermissions(this.props.permissions, PERMISSION.add))
            operations.push(
                <Button key="add" type="primary" onClick={this.onClickAdd}>
                    {this.props.intl.formatMessage({
                        id: 'queryPanel.btn.add',
                        defaultMessage: '新增'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.import))
            otherBtns.push(
                <Button key={PERMISSION.import} href={`#${routes.import.url()}`}>
                    {this.props.intl.formatMessage({
                        id: 'queryPanel.btn.import',
                        defaultMessage: '导入'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.export))
            otherBtns.push(<Export key={PERMISSION.export} exportRequest={this.props.onClickExport} />);
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.name',
                    defaultMessage: '名称'
                }),
                dataIndex: 'name',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.description',
                    defaultMessage: '描述'
                }),
                dataIndex: 'description'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'queryPanel.column.action',
                    defaultMessage: '操作'
                }),
                dataIndex: 'action',
                width: FIXED_COLUMN_WIDTH,
                fixed: 'right',
                render: (t, r) => {
                    const menus = [
                        {
                            id: PERMISSION.update,
                            children: (
                                <a key="update" data-id={r.id} onClick={this.onClickEdit}>
                                    {this.props.intl.formatMessage({
                                        id: 'queryPanel.operation.update',
                                        defaultMessage: '编辑'
                                    })}
                                </a>
                            ),
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                        },
                        {
                            id: PERMISSION.abandon,
                            children: ref =>
                                <WrappedPopconfirm
                                    id={r.id}
                                    key="abandon"
                                    title={this.props.intl.formatMessage({
                                        id: 'queryPanel.popconfirm.message',
                                        defaultMessage: '是否继续?'
                                    })}
                                    onVisibleChange={ref.setMenuVisible}
                                    onConfirm={this.handleAbandon}>
                                    <a key="abandon">
                                        {this.props.intl.formatMessage({
                                            id: 'queryPanel.operation.abandon',
                                            defaultMessage: '作废'
                                        })}
                                    </a>
                                </WrappedPopconfirm>,
                            hidden: !(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                        }
                    ];
                    return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
                }
            }
        ];
        const pagination = {
            total: this.props.total,
            pageSize: this.props.pageSize,
            current: this.props.pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        const detail = this.props.data.find(item => item.id === this.state.currentId) || {};
        return (
            <div>
                <ModeEdit
                    detail={detail}
                    onSubmit={this.onSubmit}
                    onCancel={this.onCancel}
                    showPanel={this.state.showPanel} />
                <Form className="form-standard">
                    <Row>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.code',
                                    defaultMessage: '编号'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput
                                    name="code"
                                    value={this.props.conditions.code}
                                    onPressEnter={this.props.onConditionsPressEnter}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_BIG_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.name',
                                    defaultMessage: '名称'
                                })}
                                {...FORM_BIG_OPTIONS.item}>
                                <TextInput
                                    name="name"
                                    value={this.props.conditions.name}
                                    onPressEnter={this.props.onConditionsPressEnter}
                                    onBlur={this.props.onConditionsChange} />
                            </FormItem>
                        </Col>
                        {this.props.categoryName
                            ? <Col {...FORM_BIG_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.category',
                                        defaultMessage: '分类'
                                    })}
                                    {...FORM_BIG_OPTIONS.item}>
                                    <WrappedTag className={styles.tagFontSize} color="blue"
                                        closable onClose={this.props.onCloseTag}>{this.props.categoryName}</WrappedTag>
                                </FormItem>
                            </Col> : null}
                    </Row>
                    <Row className="operation-buttons">
                        <Col span={10}>
                            <ButtonGroup>
                                <Button
                                    key="query"
                                    type="primary"
                                    onClick={this.props.querySearch}
                                    loading={this.props.loading}>
                                    {this.props.intl.formatMessage({
                                        id: 'queryPanel.btn.query',
                                        defaultMessage: '查询'
                                    })}
                                </Button>
                            </ButtonGroup>
                            <Button key="clear" onClick={this.props.onClickReset}>
                                {this.props.intl.formatMessage({
                                    id: 'queryPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}
                            </Button>
                        </Col>
                        <Col span={14} className="col-align-right">
                            <ButtonGroup>{otherBtns}</ButtonGroup>
                            {operations}
                        </Col>
                    </Row>

                    <Table
                        className="white-space-nowrap"
                        columns={columns}
                        dataSource={this.props.data}
                        rowKey="id"
                        pagination={pagination}
                        loading={this.props.loading || this.state.loading}
                        onChange={this.onChangeSort}
                        locale={locale}
                        {...TABLE} />
                </Form>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    conditions: PropTypes.object,
    intl: PropTypes.object,
    loading: PropTypes.bool,
    permissions: PropTypes.array,
    querySearch: PropTypes.func,
    onClickExport: PropTypes.func,
    onClickReset: PropTypes.func,
    onConditionsChange: PropTypes.func,
    onConditionsPressEnter: PropTypes.func,
    onSelect: PropTypes.func
};
import {connect} from 'react-redux';
import {
    saveQueryCondition,
    querySearch,
    resetQueryPanel,
    tableSearch,
    onClickAbandonInfo,
    exportData,
    onClickUpdateInfo,
    categorySearch,
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);

const getData = selectorFactory(['page', 'domainData', 'list', 'data']);

const getCategoryName = createSelector(
    state => state.getIn(['page', 'domainData', 'categories', 'data']),
    state => state.getIn(['page', 'appState', 'queryCondition', 'faultModeCategoryId']),
    (categories, categoryId) => {
        if(!categoryId)
            return '';
        const category = getObjById(categories.toJS(), categoryId);
        return category ? category.name : '';
    }
);

const mapStateToProps = state => ({
    conditions: getConditions(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    permissions: getPermissions(state),
    data: getData(state),
    errorMessage: state.getIn(['page', 'domainData', 'list', 'message']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    categoryName: getCategoryName(state),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (value, name) => dispatch(saveQueryCondition(name, value)),
    onConditionsPressEnter: (value, name) => {
        dispatch(saveQueryCondition(name, value));
        dispatch(querySearch());
    },
    querySearch: () => dispatch(querySearch()),
    onClickReset: () => dispatch(resetQueryPanel()),
    onClickExport: () => dispatch(exportData()),
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickAbandon: id =>
        dispatch(onClickAbandonInfo(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickUpdate: data => dispatch(onClickUpdateInfo(data)).then(success => {
        if(success) dispatch(tableSearch({
            pageIndex: PAGE.index
        }));
        return success;
    }),
    onCloseTag: () => dispatch(categorySearch()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(QueryPanel));
